/*
 * data.c
 *
 *  Created on: Jul 13, 2011
 *      Author: alemao
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "player.h"

static int initialized = 0;

struct list_group{
//	int class;
	player **list;
};
static struct list_group list_by_class[CLASS_TOTAL];
static struct list_group list_by_team[TOTALTEAMS];
static struct list_group list_by_team_and_class[TOTALTEAMS][CLASS_TOTAL];

extern int data_init(void)
{
	int i, j;

	if (!initialized)
	{
		initialized = 1;
		for (i=0; i<CLASS_TOTAL; i++)
			list_by_class[i].list = libplayer_createlist();
		for (i=0; i<TOTALTEAMS; i++)
			list_by_team[i].list = libplayer_createlist();
		for (i=0; i<TOTALTEAMS; i++)
			for (j=0; j<CLASS_TOTAL; j++)
				list_by_team_and_class[i][j].list = libplayer_createlist();
	}
}

extern int load_file(char *file, int rodada)
{
	player *Player;
	FILE *fd;
	char tmp[2048];
	int i;
	int jogador;

	fd = fopen(file, "r");
	if (!fd){
		printf("Error opening file: %s\n", file);
		exit(0);
	}

	while ( !feof(fd) &&  fscanf(fd, "%[^\n]", tmp)){
		Player = libplayer_parseplayer(tmp);
		if (Player){
//			printf("Player->class = %d, Player->name = %s\n", Player->class, Player->name);
			/* verifica se o jogador ja foi incluido nas listas */
			if ( (jogador = libplayer_findplayer(list_by_class[CLASSLESS].list, Player)) < 0)
			{
				/* adiciona o jogador na lista geral*/
				if (libplayer_appendtolist(&list_by_class[CLASSLESS].list, Player))
				{
					printf("error\n");
				}
				/* adiciona o jogador na lista por classe*/
				if (libplayer_appendtolist(&list_by_class[Player->class].list, Player))
				{
					printf("error\n");
				}
				/* adiciona o jogador na lista por time*/
				if (libplayer_appendtolist(&list_by_team[Player->team].list, Player))
				{
					printf("error\n");
				}
				if (libplayer_appendtolist(&list_by_team_and_class[Player->team][Player->class].list, Player))
				{
					printf("error\n");
				}
			}
			else
			{
				libplayer_freeplayer(Player);
				Player = list_by_class[CLASSLESS].list[jogador];
			}
//			for (i=0; i<ROUNDS_TOTAL;i++)
//			{
//				if (Player->statistics[i] == NULL)
//				{
//					break;
//				}
//			}
			/* carrega a estatistica da rodada do jogador*/
			Player->statistics[rodada - 1] = libplayer_parsestatistics(tmp);
		}else
			printf("libplayer_parseplayer ERROR: %s\n", tmp);
//		printf("Next\n");
		fscanf(fd, "\n");
	}
	fclose(fd);
}

extern player **get_list_byclass(int class){
	return list_by_class[class].list;
}

extern player **get_list_byteam(int team){
	return list_by_team[team].list;
}

extern player **get_list_byteamandclass(int team, int class){
	return list_by_team_and_class[team][class].list;
}
